<?php
class Model_Model
{
    static private $_table = 'model';
	static private $_modelNameID = array();
	
    public static function getCount($style)
    {
    	if($style == 0){
	        $DB  = Eren_Registry::get('DB');
	        $ret = $DB->table(self::$_table)
	                  ->count();
    	}else{
    		$DB  = Eren_Registry::get('DB');
	        $ret = $DB->table(self::$_table)
	        		  ->where('style', '=', $style)
	                  ->count();
    	}

        return $ret;
    }
    
    public static function getList($page, $style)
    {
        $pagelimit = Model_Navigate::getLimit($page, Config_Default::getModelPageSize());
        $DB  = Eren_Registry::get('DB');
        if($style == 0){
	        $ret = $DB->table(self::$_table)
	                  ->orderBy('modelid', 'DESC')
	                  ->limit($pagelimit['start'], $pagelimit['limit'])
	                  ->select();
        }else{
        	$ret = $DB->table(self::$_table)
	        		  ->where('style', '=', $style)
	                  ->orderBy('modelid', 'DESC')
	                  ->limit($pagelimit['start'], $pagelimit['limit'])
	                  ->select();
        }
        return $ret['data'];
    }

    public static function getAll()
    {
        $DB  = Eren_Registry::get('DB');
        $ret = $DB->table(self::$_table)
                  ->orderBy('modelid', 'DESC')
                  ->select();
        return $ret['data'];
    }
    
	public static function getAllTimeName()
    {
        $models = self::getAll();
        $ret = array();
        foreach($models as $model){
        	$temp['id'] = $model['modelid'];
        	$temp['name'] = $model['modelname'];
        	$temp['flg'] = 0;
        	$ret[$model['beijingstart']][] = $temp; 
        	$temp['flg'] = 1;
        	$ret[$model['beijingend']][] = $temp; 
        }
        
        return $ret;
    }
    
    public static function getAllModleState($starttime, $endtime, $starthour, $endhour, $startmin, $endmin, $workid = -1)
    {
    	$ret = array();
        $models = self::getAll();
        $works = Model_Work::getByStartEndTime($starttime, $endtime, $workid);
        $starttime = Model_Common::getStampTime($starttime);
        $endtime = Model_Common::getStampTime($endtime);
        
        if($starttime > $endtime){
        	throw new Eren_Exception("<span style='margin-top:5px;color:#FF0000'>工作日期异常，开始日期不能大于结束日期</span>", -1);
        }
        
        $tempStartTime = $starthour*60 + $startmin;
        $tempEndTime = $endhour*60 + $endmin;

        if($tempStartTime >= $tempEndTime){
        	throw new Eren_Exception("<span style='margin-top:5px;color:#FF0000'>工作时间异常，开始时间不能大于结束时间</span>", -1);
        }
        
        $modelWorks = array();
        foreach($works as $work){
        	$workStartTime = $work['starthour']*60 + $work['startmin'];
        	$workEndTime = $work['endhour']*60 + $work['endmin'];
        	if(!($workStartTime<$tempEndTime && $workEndTime>$tempStartTime))
        	{
        		continue;
        	}
        	$modelnames = explode(",", $work['modelname']);
        	foreach($modelnames as $modelname){
        		$modelWorks[$modelname][] = $work;
        	}
        }
        
        foreach($models as $key=>$model){
        	$temp = array();
        	$temp['modelid'] = $model['modelid'];
        	$temp['modelname'] = $model['modelname'];
        	$temp['illshow'] = '';
        	$temp['beijingshow'] = '';
        	$temp['work'] = array();
        	$temp['title'] = false;
        	$temp['haswork'] = false;
        	$temp['hasface'] = false;
        	$temp['disable'] = false;
        	if(!($model['beijingstart']<=$starttime && $model['beijingend'] >= $endtime)){
        			$tIllStartTime = Model_Common::getFormatTimeYMD($model['beijingstart']);
        			$tIllEndTime = Model_Common::getFormatTimeYMD($model['beijingend']);
        			$temp['beijingshow'] = "在京日期:{$tIllStartTime} 至 {$tIllEndTime}";
        			$temp['title'] = true;
        			$temp['disable'] = true;
        	}
        	if($model['illstart'] != ""){
        		if($model['illstart']<=$endtime && $model['illend'] >= $starttime){
        			$tIllStartTime = Model_Common::getFormatTimeYMD($model['illstart']);
        			$tIllEndTime = Model_Common::getFormatTimeYMD($model['illend']);
        			$temp['illshow'] = "休假日期:{$tIllStartTime} 至 {$tIllEndTime}";
        			$temp['title'] = true;
        			$temp['disable'] = true;
        		}
        	}
            if(isset($modelWorks[$model['modelname']])){
        		foreach($modelWorks[$model['modelname']] as $work){
        			$tWork = array();
        			$tWork['flg'] = $work['flg'];
        			$tStartTime = Model_Common::getFormatTimeYMD($work['starttime']);
        			$tStartHour = Model_Common::getFomrtTimeHMSByHour($work['starthour'], $work['startmin']);
        			$tEndTime = Model_Common::getFormatTimeYMD($work['endtime']);
        			$tEndHour = Model_Common::getFomrtTimeHMSByHour($work['endhour'], $work['endmin']);
        			if($tWork['flg'] == 1){
        				$tWork['time'] = "面试";
        				$temp['title'] = true;
        				$temp['hasface'] = true;
        			}else{
        				$tWork['time'] = "工作";
        				$temp['title'] = true;
        				$temp['haswork'] = true;
        			}
        			$tWork['time'] .= "日期:{$tStartTime} 至 {$tEndTime} 时间:{$tStartHour} 至 {$tEndHour}";
        			$tWork['workid'] = $work['workid'];
        			$temp['work'][] = $tWork;
        		}
        	}
        	$ret[] = $temp;
        }
        return $ret;
    }
    
    public static function getMonthWorks($modelname)
    {
    	$month = Model_Common::getFormatTimeYM();
    	$works = Model_Work::getByTime($month);
    	$ret = array();
    	foreach ($works as $work){
	        if($modelname != "" && !stristr(strtolower($work['modelname']),  strtolower($modelname))){
	                continue;
	        }
	        $temp = array();
	        $temp['workid'] = $work['workid'];
	        $temp['flg'] = $work['flg'] == 1 ? '面试':'工作';
	        $temp['starttime'] = Model_Common::getFormatTimeYMD($work['starttime']);
	        $temp['endtime'] = Model_Common::getFormatTimeYMD($work['endtime']);
	        $temp['starthour'] = Model_Common::getFomrtTimeHMSByHour($work['starthour']);
	        $temp['endhour'] = Model_Common::getFomrtTimeHMSByHour($work['endhour']);
	        $ret[] = $temp;
    	}
    	return $ret;
    }
    
    public static function getAllNameID()
    {
    	if(!empty(self::$_modelNameID)){
    		return self::$_modelNameID;
    	}
    	
        $DB  = Eren_Registry::get('DB');
        $ret = $DB->table(self::$_table)
                  ->orderBy('modelid', 'DESC')
                  ->select();
        foreach($ret['data'] as $value){
        	self::$_modelNameID[$value['modelname']] = $value['modelid'];
        }

        return self::$_modelNameID;
    }
    
    public static function getIDByName($name)
    {
    	$kv = self::getAllNameID();
    	if(!isset($kv[$name])){
    		return -1;
    	}
    	
    	return $kv[$name];
    }
    
    public static function getIDsByNameStr($name)
    {
    	$ret = array();
    	$names = explode(',', trim($name, ', '));
    	$kv = self::getAllNameID();
    	foreach($names as $v){
	    	if(isset($kv[$v])){
	    		$ret[] = $kv[$v];
	    	}
    	}

    	return implode(',', $ret);
    }
    
    public static function getNamesByIDs($modelids)
    {
        if(empty($modelids)){
            //throw new Eren_Exception('模特信息必选', -1);
            return '';
        }
        $ret = "";
        foreach($modelids as $modelid) {
            $modelInfo = self::getByID($modelid);
            if(empty($modelInfo)){
                throw new Eren_Exception('模特信息异常，请联系管理员', -1);
            }
            $ret .= "," . $modelInfo['modelname'];
        }

        return trim($ret, ",");
    }
    
    public static function getNicksByNameStr($name)
    {
    	$ret = array();
    	$names = explode(',', trim($name, ', '));
    	foreach($names as $n){
    		$n = trim($n, ' ');
    		$modelinfo = self::getByName($n);
    		if(!empty($modelinfo)){
    			$ret[] = $modelinfo['nickname'] == '' ? $modelinfo['modelname'] : $modelinfo['nickname'];
    		}
    		else
    		{
    		    $ret[] = $n;
    		}
    	}

    	return implode(',', $ret);
    }
    
    public static function getByID($modelID)
    {
        $modelID = intval($modelID);
        $model = Eren_Registry::get('DB')->table(self::$_table)
                                           ->where('modelid', '=', $modelID)
                                           ->select();
        return !isset($model['data'][0])? array():$model['data'][0];
    }
    
    public static function getByName($modelName)
    {
        $modelName = trim($modelName, "\r\n\t ");
        $model = Eren_Registry::get('DB')->table(self::$_table)
                                           ->where('modelname', '=', $modelName)
                                           ->select();
        return !isset($model['data'][0])? array():$model['data'][0];
    }
   
    public static function add($modelname, $country, $height, $bust, $waist,
                            $hip, $shoescode, $company, $beijingstart, $beijingend, 
                            $illstart, $illend, $illinfo, $media, $sytle, $nickname)
    {
    	$modelname = trim($modelname);
        if(!Model_Validator::userName($modelname)){
            throw new Eren_Exception('模特名不合法，请填写正确的模特名，只能是字母、空格和数字', -1);
        }
        
        $model = self::getByName($modelname);
        if(!empty($model)){
            throw new Eren_Exception('模特名已经存在，请更改后重试', -1);
        }
        
        $country = Model_Common::filterText($country);
        if($country == ""){
            throw new Eren_Exception('国籍必须填写', -1);
        }
        
        if(!Model_Validator::modelStyle($sytle)){
        	throw new Eren_Exception('模特类型异常', -1);
        }
        
        $height = Model_Common::filterText($height);
        if($height == ""){
            throw new Eren_Exception('身高必须填写', -1);
        }
        
        $bust = Model_Common::filterText($bust);
        if($bust == ""){
            throw new Eren_Exception('胸围必须填写', -1);
        }
            
        $waist = Model_Common::filterText($waist);
        if($waist == ""){
            throw new Eren_Exception('腰围必须填写', -1);
        }
        
        $hip = Model_Common::filterText($hip);
        if($hip == ""){
            throw new Eren_Exception('臀围必须填写', -1);
        }
        
        $shoescode = Model_Common::filterText($shoescode);
        if($shoescode == ""){
            throw new Eren_Exception('鞋码必须填写', -1);
        }
        
        $company = Model_Common::filterText($company);
        if($company == ""){
            throw new Eren_Exception('母公司必须填写', -1);
        }
        
        if(!Model_Validator::timeYMD($beijingstart)){
            throw new Eren_Exception('在京开始时间不合法', -1);
        }
        $beijingstart = Model_Common::getStampTime($beijingstart);
        
        if(!Model_Validator::timeYMD($beijingend)){
            throw new Eren_Exception('在京结束时间不合法', -1);
        }
        $beijingend = Model_Common::getStampTime($beijingend);
        
        if($beijingstart > $beijingend){
            throw new Eren_Exception('在京开始时间不能大于结束时间', -1);
        }
        
        if($illstart!="" && $illend!=""){
	        if(!Model_Validator::timeYMD($illstart)){
	            throw new Eren_Exception('休假开始时间不合法', -1);
	        }
	        $illstart = Model_Common::getStampTime($illstart);
	        
	        if(!Model_Validator::timeYMD($illend)){
	            throw new Eren_Exception('休假结束时间不合法', -1);
	        }
	        $illend = Model_Common::getStampTime($illend);
	        
	        if($illstart > $illend){
            	throw new Eren_Exception('在休假开始时间不能大于结束时间', -1);
       		}
        	$illinfo = Model_Common::filterText($illinfo);
        }else if($illstart!="" || $illend!=""){
        	throw new Eren_Exception('休假时间必须全填或全不填写', -1);
        }

        $media = trim($media, "\r\n\t ,");
        /*if($media == ""){
            throw new Eren_Exception('必须上传图片', -1);
        }*/
        
        $fields['modelname']           = $modelname;
        $fields['nickname']            = trim($nickname, "\r\n ");
        $fields['country']             = $country;
        $fields['height']              = $height;
        $fields['bust']                = $bust;
        $fields['waist']               = $waist;
        $fields['hip']                 = $hip;
        $fields['shoescode']           = $shoescode;
        $fields['company']             = $company;
        $fields['beijingstart']        = $beijingstart;
        $fields['beijingend']          = $beijingend;
        $fields['illstart']            = $illstart;
        $fields['illend']              = $illend;
        $fields['illinfo']             = $illinfo;
        $fields['media']               = $media;
        $fields['style']               = $sytle;
        $fields['createdtime']         = Model_Common::getNowTime();
        
        $ret = Eren_Registry::get('DB')->table(self::$_table)->insert($fields);
        $log = var_export($fields, true);
        Model_Log::write("[modelid:{$ret}][add][{$log}]");
        return $ret;
    }
    
    public static function update($modelID, $country, $height, $bust, $waist,
                            $hip, $shoescode, $company, $beijingstart, $beijingend, 
                            $illstart, $illend, $illinfo, $media, $sytle, $nickname)
    {
        $modelID = intval($modelID);
        $model = self::getByID($modelID);
        if(empty($model)){
            throw new Eren_Exception('修改的模特信息不存在', -1);
        }
        
        $country = Model_Common::filterText($country);
        if($country == ""){
            throw new Eren_Exception('国籍必须填写', -1);
        }

        if(!Model_Validator::modelStyle($sytle)){
        	throw new Eren_Exception('模特类型异常', -1);
        }
        
        $height = Model_Common::filterText($height);
        if($height == ""){
            throw new Eren_Exception('身高必须填写', -1);
        }
        
        $bust = Model_Common::filterText($bust);
        if($bust == ""){
            throw new Eren_Exception('胸围必须填写', -1);
        }
            
        $waist = Model_Common::filterText($waist);
        if($waist == ""){
            throw new Eren_Exception('腰围必须填写', -1);
        }
        
        $hip = Model_Common::filterText($hip);
        if($hip == ""){
            throw new Eren_Exception('臀围必须填写', -1);
        }
        
        $shoescode = Model_Common::filterText($shoescode);
        if($shoescode == ""){
            throw new Eren_Exception('鞋码必须填写', -1);
        }
        
        $company = Model_Common::filterText($company);
        if($company == ""){
            throw new Eren_Exception('母公司必须填写', -1);
        }
        
        if(!Model_Validator::timeYMD($beijingstart)){
            throw new Eren_Exception('在京开始时间不合法', -1);
        }
        $beijingstart = Model_Common::getStampTime($beijingstart);
        
        if(!Model_Validator::timeYMD($beijingend)){
            throw new Eren_Exception('在京结束时间不合法', -1);
        }
        $beijingend = Model_Common::getStampTime($beijingend);
        
        if($beijingstart > $beijingend){
            throw new Eren_Exception('在京开始时间不能大于结束时间', -1);
        }
        
        if($illstart!="" && !Model_Validator::timeYMD($illstart)){
            throw new Eren_Exception('休假开始时间不合法', -1);
        }
        $illstart = Model_Common::getStampTime($illstart);
        
        if($illend!="" && !Model_Validator::timeYMD($illend)){
            throw new Eren_Exception('休假结束时间不合法', -1);
        }
        $illend = Model_Common::getStampTime($illend);
                
        if($illstart > $illend){
            throw new Eren_Exception('在休假开始时间不能大于结束时间', -1);
        }
        
        $illinfo = Model_Common::filterText($illinfo);

        $media = trim($media, "\r\n\t ,");
        /*if($media == ""){
            throw new Eren_Exception('必须上传图片', -1);
        }*/
        
        $fields['nickname']            = trim($nickname, "\r\n ");
        $fields['country']             = $country;
        $fields['height']              = $height;
        $fields['bust']                = $bust;
        $fields['waist']               = $waist;
        $fields['hip']                 = $hip;
        $fields['shoescode']           = $shoescode;
        $fields['company']             = $company;
        $fields['beijingstart']        = $beijingstart;
        $fields['beijingend']          = $beijingend;
        $fields['illstart']            = $illstart;
        $fields['illend']              = $illend;
        $fields['illinfo']             = $illinfo;
        $fields['media']               = $media;
        $fields['style']               = $sytle;
        
        Eren_Registry::get('DB')->table(self::$_table)->where('modelid', '=', $modelID)->update($fields);
        $log = var_export($fields, true);
        Model_Log::write("[modelid:{$modelID}][update][{$log}]");
        return TRUE;
    }
    
    public static function delete($modelID)
    {
        $modelID     = intval($modelID);
        $model       = self::getByID($modelID);
        if(empty($model)){
            throw new Eren_Exception('删除的模特不存在', -1);
        }
        $log = var_export($model, true);
        Eren_Registry::get('DB')->table(self::$_table)->where('modelid', '=', $modelID)->delete();
        Model_Log::write("[modelid:{$modelID}][delete][{$log}]");
        return TRUE;
    }
    
    public static function getModelStyleName($id)
    {
    	$styles = Config_Default::getModelStyle();
    	if(isset($styles[$id])){
    		return $styles[$id];	
    	}
    	
    	return false;
    }
}
